/*
 * Sesame Inc.
 * Copyright (c) 2009 All Rights Reserved.
 */
package com.sesame.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.sesame.domain.Album;
import com.sesame.domain.Image;
import com.sesame.domain.User;
import com.sesame.service.AlbumService;
import com.sesame.service.UserService;

/**
 * @author r6c
 * 
 */
public class EditImageController extends SimpleFormController {

    private AlbumService albumService;
    private Integer userId;
    private List<Album> albumList;
    private Integer imageId = null;

    public void setAlbumService(AlbumService albumService) {
        this.albumService = albumService;
    }

    protected Map referenceData(HttpServletRequest request) throws Exception {
        Map referenceData = new HashMap();
        userId = (Integer) request.getSession().getAttribute("userId");
        albumList = albumService.listAllAlbum(userId);
        imageId = Integer.parseInt(request.getParameter("imageId"));
        Image image = albumService.showImage(imageId);
        referenceData.put("image", image);
        referenceData.put("albumList", albumList);
        return referenceData;
    }

    protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {

        Image image = (Image) command;
        image.setId(imageId);
        image.setUserId(userId);
        image.setPrivacy(albumService.showAlbum(image.getAlbumId())
                .getPrivacy());
        image.setModTime(new Date());

        Map model = errors.getModel();

        if (albumService.isEditImage(image, model)) {
            return new ModelAndView("redirect:imageDetail.html?imageId="
                    + imageId);
        } else {
            return new ModelAndView(getFormView(), model);
        }

    }

}